package com.pearl.security.multiloginreject.demo.session.memery;

import cn.hutool.core.util.StrUtil;
import com.pearl.security.multiloginreject.demo.util.LoginUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import java.io.IOException;

/**
 * @author TD
 * @version 1.0
 * @date 2024/5/14
 */
public class PearlSessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {

    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        // 获取设备
        Object principal = event.getSessionInformation().getPrincipal();
        String device = LoginUtils.parseDevice(principal);
        // 失败处理器，跳转到登录页并显示错误信息
        SimpleUrlAuthenticationFailureHandler simpleUrlAuthenticationFailureHandler = new SimpleUrlAuthenticationFailureHandler("/login?error");
        HttpServletRequest request = event.getRequest();
        HttpServletResponse response = event.getResponse();
        AccountExpiredException exception = new AccountExpiredException(StrUtil.format("当前用户已在其他{}设备登录", device));
        simpleUrlAuthenticationFailureHandler.onAuthenticationFailure(request, response, exception);
    }
}
